package com.lanou.horo.zhuizhui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.lanou.horo.zhuizhui.activity.DetailsActivity;
import com.lanou.horo.zhuizhui.adapter.CommunityPEFAdapter;
import com.lanou.horo.zhuizhui.entity.CommunityPageEssenceItem;
import com.lanou.horo.zhuizhui.entity.EveryDayItem;
import com.lanou.horo.zhuizhui.utility.customDialog.CustomProgressDialog;
import com.lanou.horo.zhuizhui.utility.clickInterface.EveryDayClick;
import com.lanou.horo.zhuizhui.utility.imageLoader.GetVolleyData;
import com.lanou.horo.zhuizhui.utility.recyclerView.SpacesItemDecoration;
import com.lanou.horo.zhuizhui.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/24.
 */
public class CommunityPageEssenceFragment extends Fragment implements EveryDayClick, SwipeRefreshLayout.OnRefreshListener {
    private RecyclerView recyclerView;
    private CommunityPEFAdapter adapter;
    private RequestQueue queue;
    private RecyclerViewHeader header;
    private ImageView topImg;
    private String url;
    private SwipeRefreshLayout swipeRefreshWidget;
    private CustomProgressDialog dialog;
    private int lastVisibleItem;
    private boolean isdialogshowing = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    swipeRefreshWidget.setRefreshing(true);
                    if (adapter.getEntityList() != null) {
                        adapter.getEntityList().clear();
                        initData();
                    }
                    break;
            }
        }
    };
    ;

    public CommunityPageEssenceFragment(String api) {
        url = api;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_essence, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.essenceRecyclerView);
        header = (RecyclerViewHeader) view.findViewById(R.id.communityHeader);
        topImg = (ImageView) view.findViewById(R.id.communityTopimg);
        swipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.communitypageSwipeRefresh);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        dialog = new CustomProgressDialog(getActivity(), "加载中...", R.anim.loding);
        dialog.setCanceledOnTouchOutside(false);

        swipeRefreshWidget.setColorSchemeColors(0xff00aa00, 0xffaa0000, 0xff0000aa, 0xff654321);
        swipeRefreshWidget.setOnRefreshListener(this);
        swipeRefreshWidget.setProgressViewOffset(true, -30, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources()
                        .getDisplayMetrics()));
        swipeRefreshWidget.setProgressViewEndTarget(true, 100);

        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new CommunityPEFAdapter(getContext());
        adapter.clickItemView(this);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 1);
        manager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(manager);
        header.attachTo(recyclerView, true);
        recyclerView.setAdapter(adapter);
        int spacingInPixels = 20;
        recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
    }


    public void initData() {

        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }

        queue = Volley.newRequestQueue(getActivity());

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Gson gson = new Gson();
                CommunityPageEssenceItem cpei = gson.fromJson(response, CommunityPageEssenceItem.class);
                if (cpei != null) {
                    List<CommunityPageEssenceItem.TopicsEntity> entities = cpei.getTopics();
                    if (entities != null && entities.size() > 0) {
                        adapter.addTopList(entities);
                    }
                    List<CommunityPageEssenceItem.BannersEntity> list = cpei.getBanners();
                    if (list != null && list.size() > 0) {
                        String url = list.get(0).getCover();
                        GetVolleyData.getBitmapRequest(url, topImg, 1000, 1000);
                    }
                }
                swipeRefreshWidget.setRefreshing(false);
                if (isdialogshowing == true) {
                    dialog.dismiss();
                    isdialogshowing = false;
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders()
                    throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        queue.add(request);

    }

    @Override
    public void everyDayItemClick(EveryDayItem.ThemeListEntity url) {
    }

    @Override
    public void communityItemClick(CommunityPageEssenceItem.TopicsEntity top) {
        Intent intent = new Intent(getActivity(), DetailsActivity.class);
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        if (isdialogshowing == false) {
            dialog.show();
            isdialogshowing = true;
        }
        handler.sendEmptyMessageDelayed(0, 3000);

    }

}

